<template>
    <view class="page page__index">
        <view class="page__content">
            <view
                v-if="downloadUrl || localFile"
                class="package-info"
            >
                <view
                    v-if="downloadUrl"
                    class="package-info__item"
                >
                    <view class="package-info__label">下载地址：</view>
                    <view class="package-info__content">{{downloadUrl}}</view>
                </view>
                <view
                    v-if="localFile"
                    class="package-info__item"
                >
                    <view class="package-info__label">本地文件：</view>
                    <view class="package-info__content">{{localFile}}</view>
                </view>
            </view>

            <view
                v-if="localFile"
                class="input__container"
            >
                <input
                    v-model="deviceId"
                    type="text"
                    placeholder="请输入设备MAC"
                >
            </view>

            <view
                v-if="showDownloadButton || localFile"
                class="button-box"
            >
                <template v-if="showDownloadButton">
                    <view
                        v-for="(item, index) in packageUrls"
                        :key="index"
                        class="button-box__item"
                    >
                        <button @click="download(index)">下载 Package {{index + 1}}</button>
                    </view>
                </template>
                <view
                    v-else
                    class="button-box__item"
                >
                    <button @click="clearDownload">重新下载</button>
                </view>

                <view
                    v-if="localFile"
                    class="button-box__item"
                >
                    <button @click="doDfu">开始DFU</button>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
// #ifdef APP-PLUS
const nrfDfu = uni.requireNativePlugin("UUCoder-nRF-DFU");
// #endif

function log() {
    console.log(...arguments);

    // #ifdef APP-PLUS
    const log = [...arguments].map(item => JSON.stringify(item)).join(" ");
    nrfDfu.log(log);
    // #endif
}

const DFU_PACKAGE_URL = [
    "https://ehealth.diaolanhua.com/uploads/static/dfu/ZJUT_THE.zip",
    "https://ehealth.diaolanhua.com/uploads/static/dfu/ZJUT_PWD.zip"
];

export default {
    data() {
        return {
            downloading: false,
            downloadUrl: null,
            localFile: null,
            deviceId: ""
        };
    },
    computed: {
        packageUrls() {
            return Array.isArray(DFU_PACKAGE_URL) ? DFU_PACKAGE_URL : [];
        },
        showDownloadButton() {
            return !this.downloadUrl && this.packageUrls.length > 0;
        }
    },
    methods: {
        download(index) {
            if (this.downloading) return;
            if (!Number.isInteger(index) || index < 0) return;

            const url = this.packageUrls[index];
            if (!/^http/i.test(url)) return;

            this.downloadUrl = url;
            this.downloading = true;
            uni.showLoading({
                title: "正在下载"
            });
            uni.downloadFile({
                url,
                success: res => {
                    if (res.statusCode >= 200 && res.statusCode < 300) {
                        log("文件下载完成：", res.tempFilePath);

                        plus.io.resolveLocalFileSystemURL(
                            res.tempFilePath,
                            entry => {
                                const path = entry.toLocalURL();
                                this.downloading = false;
                                uni.hideLoading();
                                this.localFile = path.replace(
                                    /^file:\/\//i,
                                    ""
                                );
                                log("文件绝对路径：", this.localFile);
                            }
                        );
                    } else {
                        this.clearDownload();
                        uni.showToast({
                            title: "文件下载失败",
                            icon: "none"
                        });
                    }
                },
                fail: err => {
                    this.downloading = false;
                    this.clearDownload();
                    uni.showToast({
                        title: "文件下载失败",
                        icon: "none"
                    });
                }
            });
        },
        clearDownload() {
            if (this.downloading) return;

            this.downloadUrl = null;
            this.localFile = null;
            this.deviceId = "";
        },
        doDfu() {
            if (!this.localFile) {
                uni.showToast({
                    title: "请先下载DFU包",
                    icon: "none"
                });
                return;
            }

            if (!/^[0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5}$/.test(this.deviceId)) {
                uni.showToast({
                    title: "请输入正确的设备MAC",
                    icon: "none"
                });
                return;
            }

            // #ifdef APP-PLUS
            log(`对设备${this.deviceId}执行DFU: `, this.localFile);
            const result = nrfDfu.dfu(this.deviceId, this.localFile, event => {
                log("callback: " + JSON.stringify(event));
                if (event && event.method) {
                    switch (event.method) {
                        case "onDeviceConnecting":
                            log(
                                "onDeviceConnecting: ",
                                event.data.deviceAddress
                            );
                            break;
                        case "onDeviceConnected":
                            log(
                                "onDeviceConnected: ",
                                event.data.deviceAddress
                            );
                            break;
                        case "onDeviceDisconnecting":
                            log(
                                "onDeviceDisconnecting: ",
                                event.data.deviceAddress
                            );
                            break;
                        case "onDeviceDisconnected":
                            log(
                                "onDeviceDisconnected: ",
                                event.data.deviceAddress
                            );
                            break;
                        case "onDfuProcessStarting":
                            log(
                                "onDfuProcessStarting: ",
                                event.data.deviceAddress
                            );
                            break;
                        case "onDfuProcessStarted":
                            log(
                                "onDfuProcessStarted: ",
                                event.data.deviceAddress
                            );
                            break;
                        case "onProgressChanged":
                            log(
                                "onProgressChanged: ",
                                JSON.stringify(event.data)
                            );

                            uni.showLoading({
                                title: "DFU: " + event.data.percent + "%"
                            });
                            break;
                        case "onDfuCompleted":
                            log("onDfuCompleted: ", event.data.deviceAddress);

                            uni.showToast({
                                title: "DFU Completed",
                                icon: "success"
                            });
                            break;
                        case "onDfuAborted":
                            log("onDfuAborted: ", event.data.deviceAddress);

                            uni.hideLoading();
                            break;
                        case "onError":
                            log("onError: ", JSON.stringify(event.data));

                            uni.hideLoading();
                            break;
                    }
                }
            });

            log("DFU执行结果：", result);
            result
                ? uni.showLoading({
                      title: "DFU..."
                  })
                : uni.showToast({
                      title: "DFU执行失败",
                      icon: "none"
                  });
            // #endif
        }
    }
};
</script>

<style lang="scss" scoped>
.page {
    &__content {
        padding: 40rpx 32rpx;
    }

    .package-info {
        &__item {
            display: flex;

            &:not(:first-child) {
                margin-top: 20rpx;
            }
        }

        &__label {
            white-space: nowrap;
        }

        &__content {
            flex: 1;
            word-break: break-all;
        }
    }

    .input__container {
        &:not(:first-child) {
            margin-top: 40rpx;
        }

        input {
            height: 88rpx;
            padding: 0 32rpx;
            border-radius: 8rpx;
            border: 1px solid #bbb;
        }
    }

    .button-box {
        &:not(:first-child) {
            margin-top: 40rpx;
        }

        &__item {
            &:not(:first-child) {
                margin-top: 40rpx;
            }
        }
    }
}
</style>
